<template>
    <div class="container">
        <m-header :closeFn="onClose">{{barTitle}}</m-header>
        <div class="main">
            <div class="info-wrap">
                <div class="title">基本信息</div>
                <div class="content">
                    <div class="cell" v-for="(item,index) in fieldList" :key="index">
                        <m-form
                                ref="formRef"
                                :field="item"
                                @change="onChange"
                                :value="mValue[item.field_id]"
                                :disabled="disabled"
                        ></m-form>
                    </div>
                    <div class="cell">
                        <div class="label">照片样本</div>
                        <div class="value" @click="previewQr"><img ref="demoImg" src="@/assets/images/pic_demo.jpg" alt=""></div>
                    </div>
                </div>
            </div>

        </div>
        <div class="footer">
            <van-button class="btn" color="#24C373" v-show="disabled" plain @click="onEdit">修改乘车人信息</van-button>
            <van-button class="btn" color="#24C373" v-show="!disabled" @click="onSave" v-prevent-re-click>保存乘车人信息</van-button>
        </div>
    </div>
</template>

<script>
  import form from '@/components/form/form'
  import {getIdentificationType,addPassenger,editPassenger,getSchool,getLeaveSchoolType} from "../../request/api";
  import {mapState} from 'vuex'
  import {preventReClick} from "../../utils/plugins";
  import {ImagePreview} from 'vant'

  export default {
    name: "passengerDetail",
    components: {
      "m-form": form,
      [ImagePreview.Component.name]: ImagePreview.Component
    },
    props: ['value','add'],
    watch: {
      value: {
        handler(val){
          if (!val) return;
          if (Object.keys(val).length) {
            this.isEdit = true;
            let obj = {passengers_id: val.passengers_id}
            this.fieldList.forEach(item => {
              obj[item.field_id] = val[item.field_id];
            })
            this.mValue = obj;
            this.disabled = true;
          } else {
            this.isEdit = false;
            this.mValue = {sex: '男'};
            this.disabled = false;
          }
        },
        immediate: true,
        deep:true
      }
    },
    computed:{
      ...mapState({
        customerId: state => state.user.customerId
      }),
      barTitle(){
        return this.add ? '添加乘车人信息' : '乘车人详情'
      }
    },
    data(){
      return {
        // barTitle: '添加乘车人信息',
        fieldList: [
          {
            label: '乘车人姓名',
            type: 'text',
            field_id: 'passengers_name',
            rule: [{required: true}],
          },
          {
            label: '性别',
            type: 'radio',
            defaultValue: '男',
            options: [
              {name: '男',id: '男'},
              {name: '女',id: '女'}
            ],
            field_id: 'sex',
            rule: [{required: true}],
          },
          {
            label: '证件类型',
            type: 'picklist',
            options: [],
            field_id: 'identification_type_name',
            entityKey: 'identification_type_name',
            rule: [{required: true}],
          },
          {
            label: '证件号',
            type: 'text',
            field_id: 'identification_no',
            rule: [{required: true},{validator: (val) => {
              if (this.mValue.identification_type_name !== '身份证') {
                return true;
              }
                let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
                let _IDre15 =  /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
                // 校验身份证：
                return _IDRe18.test( val ) || _IDre15.test( val )

              }}],

          },
          /*{
            label: '学校',
            type: 'picklist',
            options: [],
            field_id: 'school_name',
            entityKey: 'school_name',
          },*/
          {
            label: '年级班级',
            type: 'text',
            // placeholder: '请输入例如：六年级一班 输入601',
            placeholder: '请输入年级班级',
            field_id: 'class_',
            rule: [
              {required: true},
              // {pattern: /^[0-9]{3,4}$/}  //取消数字限制
              ],
          },
          {
            label: '监护人手机',
            type: 'number',
            field_id: 'guardian_phone',
            rule: [{required: true},{pattern: /^1[3456789]\d{9}$/}],
          },
          {
            label: '乘车人照片',
            message: '近期清晣正面头部照片',
            type: 'picture',
            field_id: 'pictures_link',
            // rule: [{required: true}],
            picLimit: 1
          },

        ],
        mValue: {},
        disabled: false,
        isEdit: false,

      }
    },

    methods: {
      onChange(e){
        let {field,val} = e,
          {field_id} = field;
        let obj = {[field_id]: val};
        if (field.field_id === 'identification_type_name'){
          obj.identification_type_id = val.identification_type_id;
          obj[field_id] = val.identification_type_name;
        }
       /* if (field.field_id === 'school_name'){
          obj.school_id = val.school_id;
          obj[field_id] = val.school_name;
        }*/
        if (field.field_id === 'leave_school_name'){
          obj.leave_school_id = val.leave_school_id;
          obj[field_id] = val.leave_school_name;
        }

        this.mValue = {...this.mValue,...obj};

      },
      onEdit(){
        this.disabled = false;
      },
      onClose(){
        this.$emit('close');
      },
      onSave(){
        if (this.validAll()){
          this.$Loading();
          let {customerId,isEdit} = this,
            param = {...this.mValue,customer_id: customerId},
            api;
          if (isEdit) {
            api = editPassenger
          }else {
            api = addPassenger
          }
          api(param).then(res =>{
            if (res.errcode !== 0)return;
            this.$toast.clear();
            this.$emit('close',true);
          })
        }
      },
      validAll(){
        let isValids = [];
        this.$refs.formRef.forEach(item => {
          item.valid(item => isValids.push(item) )
        });
        return !isValids.some(item => !item)
      },

      //  预览图片
      previewQr(url){
        ImagePreview({
          images: [this.$refs.demoImg.src],
          showIndex: false,
          overlayStyle: {
            "background": "rgba(0,0,0,0.5)"
          }
        });
      }
    },
    mounted(){
      getIdentificationType().then(res => {
        if (res.errcode !== 0)return;
        this.fieldList[2].options = res.row;
      });
      getSchool().then(res => {
        if (res.errcode !== 0)return;
        this.fieldList[4].options = res.row;
      });
    }
  }
</script>

<style scoped lang="less">
    .main{
        padding: 10px;
        overflow: auto;

        .cell{
            display: flex;
            align-items: center;

            .label{
                font-size: 15px;
                color: #999;
            }
            .value{
                flex: 1;
                width: 0;
                & > img{
                    width: 100%;
                }
            }
        }
    }
    .footer{
        padding: 10px;
        .btn{
            width: 100%;}
    }
</style>
